package com.biz.primus.ms.base.service;

import com.biz.primus.base.redis.util.SimpleDataRedisDao;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.time.FastDateFormat;

import java.text.DecimalFormat;
import java.util.Date;


/**
 *
 * @author yanweijin
 */
public class SequenceGenerator extends SimpleDataRedisDao {
	
	
	//25小时,单位: 秒
	private final int oneday = 25 * 60 * 60;

	private String codeDateFormat = "yyMMdd";

	private FastDateFormat dateFormat = FastDateFormat.getInstance(codeDateFormat);

	private String pattern = "000000000000";

	@AllArgsConstructor
	public enum CodeType{
		orders("SOD"),
		tms("TMS"),
		returns("SRT"),
		payments("SPY");
		private String prefix;
	}

	/**
	 * 相同prefix共享序列,序列号长度为5
	 * @param codeType
	 * @return
	 */
	public String generateNextCode(CodeType codeType){
		return generateNextCode(codeType.prefix,5);
	}

	/**
	 * 相同prefix共享序列
	 * @param prefix
	 * @param sequenceLength 序列长度
	 * @return
	 */
	public String generateNextCode(String prefix,int sequenceLength){
		return generateNextCode(prefix,prefix,sequenceLength);
	}

	/**
	 * 相同相同的redisKey共享序列
	 * @param redisKey
	 * @param prefix
	 * @param sequenceLength 序列长度
	 * @return
	 */
	public String generateNextCode(String redisKey, String prefix,int sequenceLength){
		String dateToken = dateFormat.format(new Date());
		Integer seq = nextSequence(redisKey, dateToken);
		sequenceLength = Math.min(pattern.length(),sequenceLength);
		String seqString = new DecimalFormat(pattern.substring(0,sequenceLength)).format(seq);
		return prefix+dateToken+seqString;
	}


	public Integer nextSequence(String sequenceTag, String dateToken){
		String key = "sequence:soa:"+sequenceTag+":"+dateToken+":";
		return incrAndExpire(key);
	}

	private int incrAndExpire(String key){
		int i = incr(key).intValue();
		if(i==1){
			expire(key,oneday);
		}
		return i;
	}

}
